//
//  WmcBrandLibraryVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/6/9.
//

import RxRelay
import UIKit
import YPBedrock

class WmcBrandLibraryVM: WmcBaseVM {
    // Internal

    // MARK: 输出

    /// 数组Relay
    let listRelay: BehaviorRelay<[WmcMediaEnterpriseLogoModel.LogoData]> = .init(value: [])

    // MARK: 回调

    /// 选择Logo回调
    var didSelectLogoBlock: YPBlock.OneParam<WmcMediaEnterpriseLogoModel.LogoData>?

    // MARK: 输入

    override func config() {
        pageSize = 20
    }

    /// 刷新数据
    func refreshData() {
        page = 1
        WmcMediaWatermarkAPI.fetchEnterpriseLogo(searchText, page: page, pageSize: pageSize).subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.listRelay.accept(value.data)
            weakSelf.refreshRelay.accept(.end)
        }).disposed(by: rx.disposeBag)
    }

    /// 加载更多数据
    func loadMoreData() {
        page += 1
        WmcMediaWatermarkAPI.fetchEnterpriseLogo(searchText, page: page, pageSize: pageSize).subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            let list = value.data
            if list.isEmpty || list.count < weakSelf.pageSize {
                weakSelf.refreshRelay.accept(.noMore)
            } else {
                let newList = weakSelf.listRelay.value + list
                weakSelf.listRelay.accept(newList)
                if list.count < weakSelf.pageSize {
                    weakSelf.refreshRelay.accept(.noMore)
                } else {
                    weakSelf.refreshRelay.accept(.end)
                }
            }
        }).disposed(by: rx.disposeBag)
    }

    /// 搜索数据
    func searchData(_ text: String) {
        searchText = text
        yp.delayLast(0.3) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.requestLogoData(text)
        }
    }

    // Private

    /// 搜索字段
    var searchText: String = ""

    private func requestLogoData(_ text: String) {
        WmcHudManager.loading()
        page = 1
        WmcMediaWatermarkAPI.fetchEnterpriseLogo(text, page: page, pageSize: pageSize).subscribe(onNext: { [weak self] value in
            WmcHudManager.dismiss()
            guard let weakSelf = self else { return }
            weakSelf.listRelay.accept(value.data)
            weakSelf.refreshRelay.accept(.end)
        }).disposed(by: rx.disposeBag)
    }
}
